package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/** Redis实现全局唯一ID
 * date: 2023/9/11 19:43
 * author: MR.孙
 */
@Component
public class RedisIdWorker {

    public final static long BEGIN_TIMESTAMP = 1694461945; //2023-9-11的时间戳

    private static final int COUNT_BITS = 32; //序列号的位数


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成全局唯一id【1符号位 31bit时间戳(当前时间-起始时间计算的)  32bit递增的序列号(每秒2的32次方个不同的id)】
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;

        // 生成时间序列号 【不推荐使用固定的key，因为随着increment大小限制是2的64次方】
        // 采用前缀 + 业务 + 当天时间拼接的key 来递增 方便进行统计
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //拼接时间戳和序列号部分
        return timeStamp << COUNT_BITS | count;
    }

    // public static void main(String[] args) {
    //     // LocalDateTime now = LocalDateTime.now();
    //     // long nowTime = now.toEpochSecond(ZoneOffset.UTC);
    //     // System.out.println(nowTime);
    // }

    // private ExecutorService executorService = Executors.newFixedThreadPool(500);

    /**
     * 测试全局唯一id性能，采用多线程方式生成60000个id 花费3s左右
     * @throws InterruptedException
     */
   /* @PostConstruct
    public void test() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(300);
        //测试生成全局唯一id的性能
        long start = System.currentTimeMillis();

        for (int i = 0; i < 300; i++) {
            executorService.submit(()->{
                for (int j = 0; j < 100; j++) {
                    long id = nextId("order");
                    System.out.println("id->:" + id);
                }
                countDownLatch.countDown();
            });
        }
        //阻塞主线程，等待所以线程执行完成完成耗时
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("time->:" + (end - start));

    }*/


}
